package RMI.rtdgTOadmin.impl;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.apache.log4j.Priority;

import properties.PropertyManager;

import manager.ServiceManager;
import enums.RTDGRequestType;

import RMI.rtdgTOadmin.NetworkService;
import RMI.rtdgTOadmin.informations.SenderInformations;


public class Sender {
	
	SenderInformations informations;
	
	public SenderInformations getInformations() {
		return informations;
	}

	public void setInformations(SenderInformations informations) {
		this.informations = informations;
	}

	public void send(RTDGRequestType requestType, String ipAddress, Integer registryPortNumber) throws RemoteException {

		ServiceManager.printLog(Priority.INFO_INT, PropertyManager.properties.getProperty("rmiSend"));
		RMIComServerObject rmiComServerObject = 
				new RMIComServerObject(ServiceManager.thisHost);
		
		try {
			int clientPort = informations.getClientPortNumber();
			int registryPort = registryPortNumber;
			String registryHost = ipAddress;
			String networkServiceBindingName = NetworkService.AdminNetworkServiceBindingName;
			UnicastRemoteObject.exportObject(rmiComServerObject, clientPort);
			Registry remoteRegistry = LocateRegistry.getRegistry(registryHost, registryPort);
			NetworkService remoteService = (NetworkService)remoteRegistry.lookup(networkServiceBindingName);
			switch (requestType) {
			case REGISTER:
				ServiceManager.printLog(Priority.INFO_INT, PropertyManager.properties.getProperty("rmiRegisterRquest"));
				remoteService.register(rmiComServerObject);
				break;
			case UNREGISTER:
				ServiceManager.printLog(Priority.INFO_INT, PropertyManager.properties.getProperty("rmiUnregisterRequest"));
				remoteService.unregister(rmiComServerObject);
				break;
			default: 
				ServiceManager.printLog(Priority.INFO_INT, PropertyManager.properties.getProperty("rmiRequestNotSupported"));
				break;
			}
			
		} catch (RemoteException e) {
			ServiceManager.printLog(Priority.FATAL_INT, PropertyManager.properties.getProperty("rmiSenderRemoteException"));
			e.printStackTrace();
			System.exit(0);
		} catch (NotBoundException e) {
			ServiceManager.printLog(Priority.FATAL_INT, PropertyManager.properties.getProperty("rmiSenderAlreadyBoundException"));
			e.printStackTrace();
			System.exit(0);
		}
	}
}

